package com.zebra.gateway;

import com.zebra.gateway.processor.ClientHandlerProcessor;
import com.zebra.gateway.protocol.GatewayCommand;
import com.zebra.remoting.CommandHandler;
import com.zebra.remoting.NotifyProxy;
import com.zebra.remoting.config.BasisCommandCode;
import com.zebra.remoting.connection.Connection;
import com.zebra.remoting.protocol.PoolType;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;

import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;

public class CommandClientHandler implements CommandHandler {
    private static final InternalLogger logger = InternalLoggerFactory.getInstance(CommandClientHandler.class);

    private ClientHandlerProcessor clientHandlerProcessor;
    public CommandClientHandler(){
        clientHandlerProcessor =  new ClientHandlerProcessor();
    }

    @Override
    public void handleCommand(ChannelHandlerContext ctx, Object msg) throws Exception {
        GatewayCommand message = (GatewayCommand) msg;
        if (BasisCommandCode.PING.cmd() == message.getCmd()) {
            message.getMsgBuf().release();
            return;
        }

        //向TMS 链接
        if (BasisCommandCode.REGISTER.cmd() == message.getCmd()) {
            message.getMsgBuf().release();
            NotifyProxy.notifyProxy.ackSyncMsg(ctx.channel(), message);
            return;
        }

        PoolType poolType = message.getPoolType();
        Executor executor = poolType.equals(PoolType.DISRUPTOR) ? GwClientProcessorManager.getInstance().getDisruptorByLong(message.getUserId()) : getDefaultExecutor();
        clientHandlerProcessor.process(ctx, message, executor);

    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Connection connection = Connection.getByChannel(ctx.channel());
        if (null == connection){
            return;
        }
        logger.info("---Client Handler TMS Channel Inactive ! Inactive connection {}", connection.toString());
        GwConfigInfoManager.getInstance().removeTmsConnection(connection);
    }

    private ExecutorService getDefaultExecutor() {
        return GwClientProcessorManager.getInstance().getDefaultExecutor();
    }


}
